#!/usr/bin/python3
# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.httpserver
import tornado.options
import tornado.log
import logging
import pathlib
import os
from logging.handlers import TimedRotatingFileHandler
from service.application import app_tdp
from service.handler.tdp_slave_handler import select_waiting_task, TdpSlaveWebsocketHandler
from service.utility.mcron import sched
from service import config, service_initialize


def init_logging():
    pathlib.Path(config.tdp_log_path).mkdir(exist_ok=True)
    log_file = pathlib.Path(config.tdp_log_path, f'tdp_{tornado.options.options.port}.log')
    # 使用TimedRotatingFileHandler处理器
    file_handler = TimedRotatingFileHandler(log_file, when="d", interval=1, backupCount=30)
    # 输出格式
    log_formatter = logging.Formatter(
        "%(asctime)s %(threadName)s [%(levelname)s]: #  %(message)s"
    )
    file_handler.setFormatter(log_formatter)
    # 将处理器附加到根logger
    root_logger = logging.getLogger()
    root_logger.addHandler(file_handler)


if __name__ == "__main__":
    tornado.options.define("port", default=8888, help="run on the given port", type=int)
    tornado.options.parse_command_line()
    # 启动定时任务
    sched.start()
    init_logging()
    # app_tdp.listen(tornado.options.options.port)

    tornado.ioloop.PeriodicCallback(select_waiting_task, 3000).start()  # 定时查询执行机的测试任务

    http_server = tornado.httpserver.HTTPServer(app_tdp)
    # http_server = tornado.httpserver.HTTPServer(app_tdp, ssl_options={
    #     "certfile": os.path.join(os.path.abspath("."), "server.crt"),
    #     "keyfile": os.path.join(os.path.abspath("."), "server.key"),
    # })
    http_server.bind(tornado.options.options.port)
    http_server.start(num_processes=1)

    tornado.ioloop.PeriodicCallback(
        TdpSlaveWebsocketHandler.check_slave_heartbeat, config.slave_heartbeat_interval/2*1000
    ).start()  # 定时向执行机发送心跳
    print(f'服务启动成功. http://127.0.0.1:{tornado.options.options.port}')
    service_initialize.init()
    tornado.ioloop.IOLoop.current().start()

